package unv.esiag.uchiha.readers;


import unv.esiag.uchiha.core.Agent;
import unv.esiag.uchiha.operations.Operation;
import unv.esiag.uchiha.subscribers.Subscriber;
import unv.esiag.uchiha.topics.STopic;
import unv.esiag.uchiha.topics.Topic;

public class DataReader implements DataListener{
	private Topic topic;
	private DataReactor reactor;
	public DataReader(Topic topic) {
		this.topic = topic;
		this.reactor = new DataReactor();
		this.reactor.addDataListener(this);
	}
	public DataReactor getReactor() {
		return this.reactor;
	}
	public Topic getTopic() {
		return this.topic;
	}
	public String getTopicName() {
		return this.topic.getName();
	}
	public void signal(final Operation ope) {
		new Thread(new Runnable() {
			public void run() {
				Operation operation = ope.clone();
				if(operation.getTarget() == Operation.TARGET_TOPIC){
					if(operation.getType() == Operation.TYPE_SETSUBSCRIBER){
						String ior = (String)operation.getData().getSerializable();
						Subscriber subscriber = Agent.getInstance().ior_to_subscriber(ior);

						
						topic.addRemoteSubscriber(subscriber);
					}else if(operation.getType() == Operation.TYPE_BOOTSTRAP){
						STopic stopic = (STopic)operation.getData().getSerializable();
						try{
							topic.createFromSTopic(stopic);
						}catch(Exception e){
							e.printStackTrace();
						}
					}else if(operation.getType() == Operation.TYPE_CREATE){
						String name = (String)operation.getData().getSerializable();
						topic.createTopic(name);
						if(operation.getSource() == Operation.SOURCE_USER){
							operation.setReplicate(true);
							try{
								topic.getDataWriter().write(operation);
							}catch(Exception e){
								e.printStackTrace();
							}
						}
					}else if(operation.getType() == Operation.TYPE_STOP){
						String ip = (String)operation.getData().getSerializable();
						System.out.println("l'instance " + ip + " va s'arreter dans 10 seconde");
					}
				}else if(operation.getTarget() == Operation.TARGET_CACHE){
					if(operation.getType() == Operation.TYPE_CREATE){
						topic.setData(operation.getData().getSerializable());
						if(operation.getSource() == Operation.SOURCE_USER){
							operation.setReplicate(true);
							try{
								topic.getDataWriter().write(operation);
							}catch(Exception e){
								e.printStackTrace();
							}
						}
					}
				}
			}
		}).start();
	}
}
